package LeetCode刷题;

import java.util.Arrays;

/**
 * @program: Java_Study
 * @author: Xiaofan
 * @createTime: 2021-10-10 16:46
 * @description: Functions of this class is
 * 民间题解：O（logN）做法：
 * ！！！！！！！！就是一句话：找左边界就是尽量往右(>=)靠去找、找右边界就是尽量往左边(<=)去靠
 * class Solution {
 *     public int[] searchRange(int[] nums, int target) {
 *         int leftIndex = binarySearch1(nums,target);
 *         int rightIndex = binarySearch2(nums,target);
 *         if(leftIndex >=0 && leftIndex < nums.length && rightIndex >=0 && rightIndex < nums.length &&
 *         nums[leftIndex] == target && nums[rightIndex] == target){
 *             return new int[]{leftIndex, rightIndex};
 *         }
 *         return new int[]{-1, -1};
 *     }
 *     public int binarySearch1(int nums[], int target){
 *         //先找左边界
 *         int left = 0;
 *         int right = nums.length - 1;
 *         int leftIndex = -2;
 *         while(left <= right){
 *             int mid = left + (right-left)/2;
 *             if(nums[mid] >= target){
 *                 //关键就是找到最左边那个大于等于target的下标，即为他的左边界
 *                 right = mid - 1;
 *                 leftIndex = mid;
 *             }else{
 *                 left = mid + 1;
 *             }
 *         }
 *         return leftIndex;
 *     }
 *     public int binarySearch2(int nums[], int target){
 *         //然后找右边界
 *         int left = 0;
 *         int right = nums.length - 1;
 *         int rightIndex = -2;
 *         while(left <= right){
 *             int mid = left + (right - left)/2;
 *             if(nums[mid] > target){
 *                 //如果当前的中点元素比target要大，就往左部分去找
 *                 right = mid - 1;
 *             }else{
 *                 //如果当前中点元素<=target，就往右边去找，直到找到右边第一个比他大的元素即停止
 *                 left = mid + 1;
 *                 rightIndex = mid;
 *             }
 *         }
 *         return rightIndex;
 *     }
 *
 * }
 **/
public class NoNoNo在排序数组中查找元素的第一个和最后一个位置 {
    public static void main(String args[]){
        System.out.println(Arrays.binarySearch(new int[]{5,5},5));
    }
    public static int[] searchRange(int[] nums, int target) {
        int len=nums.length;
        if(len==1&&target==nums[0]){
            return new int[]{0,0};
        }
        int left=-1;
        int right=-1;
        for(int i=0;i<len;i++){
            if(target==nums[i]){
                left=i;
                while(i<len&&nums[i]==target){
                    i++;
                }
                right=i-1;
                break;
            }
        }
        return new int[]{left,right};
    }
}